﻿using AJWPFAdmin.Modules.Main.Views;
using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services;
using AJWPFAdmin.Services.EF;
using Masuit.Tools.Models;
using MaterialDesignExtensions.Controls;
using MaterialDesignThemes.Wpf;
using Microsoft.EntityFrameworkCore;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using AJWPFAdmin.Core.Validation;
using Masuit.Tools;
using AJWPFAdmin.Core.Enums;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using AJWPFAdmin.Core;
using Masuit.Tools.Systems;
using Newtonsoft.Json;
using AJWPFAdmin.Core.Components.AJFilePicker.ViewModels;
using AJWPFAdmin.Core.ExtensionMethods;
using Prism.Ioc;
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView;
using Masuit.Tools.DateTimeExt;
using LiveChartsCore.SkiaSharpView.WPF;
using System.Windows;
using LiveChartsCore.VisualElements;
using LiveChartsCore.SkiaSharpView.VisualElements;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;
using System.Windows.Media;
using AJWPFAdmin.Core.Mvvm;
using AJWPFAdmin.Core.Models.EF.Tables;
using MaterialDesignExtensions.Model;
using System.Windows.Controls;
using Yitter.IdGenerator;
using AJWPFAdmin.Services.EF.TableExts;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Core.Components.Views;

namespace AJWPFAdmin.Modules.Main.ViewModels
{
    public class DataVerificationUploadFormViewModel : AnnotationValidationViewModel, IDialogAware
    {
        private string _dialogTitle;
        public string DialogTitle
        {
            get { return _dialogTitle; }
            set { SetProperty(ref _dialogTitle, value); }
        }

        private bool _saving;
        public bool Saving
        {
            get { return _saving; }
            set { SetProperty(ref _saving, value); }
        }

        private bool _loading;
        public bool Loading
        {
            get { return _loading; }
            set { SetProperty(ref _loading, value); }
        }

        private DataVerificationParams _uploadParams;
        public DataVerificationParams UploadParams
        {
            get => _uploadParams;
            set
            {
                SetProperty(ref _uploadParams, value);
            }
        }

        private AppointAPIBase _appointbase;
        public AppointAPIBase AppointAPIBase
        {
            get => _appointbase;
            set => SetProperty(ref _appointbase, value);
        }

        private DelegateCommand _saveCmd;
        public DelegateCommand SaveCmd =>
            _saveCmd ?? (_saveCmd = new DelegateCommand(ExecuteSaveCmdAsync, CanExecuteSaveCmd));

        async void ExecuteSaveCmdAsync()
        {
            if (!ValidateModel())
            {
                SaveCmd.RaiseCanExecuteChanged();
                
                AJCommonDialog.ShowDialog(new Core.Components.ViewModels.AJCommonDialogViewModel.AJCommonDialogParams
                {
                    Title = "提示",
                    Message = "表单校验失败,请检查所填数据",
                    Detail = string.Join(";", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString()))
                });
                return;
            }

            Saving = true;

            var result = await _appointSvc.API.UploadDataVerificationAsync(UploadParams);

            AJCommonDialog.ShowDialog(new Core.Components.ViewModels.AJCommonDialogViewModel.AJCommonDialogParams
            {
                Title = "提示",
                Message = result.Success
                    ? $"{_appointSvc.API.KeyDescription} 核查数据上传成功!"
                    : $"{_appointSvc.API.KeyDescription} 核查数据上传失败:{result.Message}",
                Detail = result.Data is Exception ex ? ex.StackTrace : string.Empty
            });
            

            Saving = false;
        }

        bool CanExecuteSaveCmd()
        {
            return !_appointSvc.API.AutoUploadDataVerification && !HasErrors;
        }

        public string Title => string.Empty;

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public async void OnDialogOpened(IDialogParameters parameters)
        {
            Loading = true;

            UploadParams = await DataVerificationParams.ComputeAsync(db);

            SaveCmd.RaiseCanExecuteChanged();

            Loading = false;
        }

        private DbService db;
        private AJGlobalExceptionResolvedEvent _globalExceptionEvt;
        private AppointAPISvc _appointSvc;

        public DataVerificationUploadFormViewModel(DbService dbIns,
            AppointAPISvc appointSvc,
            IEventAggregator eventAggregator)
        {
            _appointSvc = appointSvc;
            AppointAPIBase = _appointSvc.API;
            DialogTitle = "核查数据上传预览";
            _globalExceptionEvt = eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>();
            _globalExceptionEvt.Subscribe(() =>
            {
                Loading = Saving = false;
            });
            db = dbIns;

        }

    }
}

